#!/usr/bin/env python
# -*- coding: UTF-8 -*-
#__email__ = "wjx010107@163.com"
#__author__ = "weijinxing"


from api_salt import saltAPI
import os,time,traceback
from models import Minions,Minionstats
from celery import task,shared_task
from atsystem.settings import FILEPATH,CMDLOG,ROOTPATH,GROUPPATH,ACCKEYPATH,DENKEYPATH,REJKEYPATH,PREKEYPATH,MINION_ID


'''
@shared_task(name='update_cstat')
def update_cs():
    sapi = saltAPI()
    for minion in Minion.objects.all():
        params = {'client':'local', 'fun':'grains.item', 'tgt':minion.minion_id,'arg1':'id','arg2':'serialnumber','arg3':'ipv4','arg4':'nodename'}
        minion_val = sapi.saltCmd(params)[0].values()[0]
        if MINION_ID == "hostname":
            m_id=minion_val['nodename']
        elif MINION_ID == "serial-number":
            m_id=minion_val['serialnumber']
        else:
            m_id=minion_val['ipv4']

        if minion_val['id'] in m_id:
            cs_stat = 'CORRECT'
        else:
            cs_stat = 'INCORRECT'
        minion.cs_stat=cs_stat
        minion.save()




'''


@shared_task(name='update_minion')
def update_hosts_list():
    try:
        sapi = saltAPI()
        params = {'client':'local', 'fun':'grains.item', 'tgt':'*','arg1':'id','arg2':'osfinger','arg3':'productname','arg4':'nodename','arg5':'ipv4','arg6':'os','arg7':'osrelease','arg8':'serialnumber'}
        minions = sapi.saltCmd(params)[0].values()
        for minion in minions:
 #       print minion['ipv4']
            if minion.has_key('osfinger'):
                OS_type=minion['osfinger']
            else:
                OS_type=minion['os']+minion['osrelease']
            jud = Minions.objects.filter(minion_id=minion['id'])
            if not jud.values():
                if MINION_ID == "hostname":
                    m_id=minion['nodename']
                elif MINION_ID == "serial-number":
                    m_id=minion['serialnumber']
                else:
                    m_id=minion['ipv4']

                if minion['id'] in m_id:
                    cs_stat = 'CORRECT'
                else:
                    cs_stat = 'INCORRECT'
                m=Minions(minion_id=minion['id'],os_type=OS_type,productname=minion['productname'],ipaddr=minion['ipv4'][0],hostname=minion['nodename'],cs_stat=cs_stat)
                m.save()
            else:
                pass
#            print 'cunzaile'
    except:
        f=open(CMDLOG+os.path.sep+'task_error.log','a')
        traceback.print_exc(file=f)
        f.flush()
        f.close()
    tady = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
    log = open(CMDLOG+os.path.sep+'task_update_minion.log','a')
    log.write('\n'+tady+'  minion update ok!')
    log.close()


@shared_task(name='update_minionkey')
def update_minionkey():
    acc = Minionstats.objects.get(keyname='acc_key')
    acc.keynum=len(os.listdir(ACCKEYPATH))
    acc.save()
    pre = Minionstats.objects.get(keyname='pre_key')
    pre.keynum=len(os.listdir(PREKEYPATH))
    pre.save()
    rej = Minionstats.objects.get(keyname='rej_key')
    rej.keynum=len(os.listdir(REJKEYPATH))
    rej.save()
    den = Minionstats.objects.get(keyname='den_key')
    den.keynum=len(os.listdir(DENKEYPATH))
    den.save()
    all = Minionstats.objects.get(keyname='all_key')
    all.keynum=acc.keynum+pre.keynum+rej.keynum+den.keynum
    all.save()
    tady = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
    log = open(CMDLOG+os.path.sep+'task_update_minion_key.log','a')
    log.write('\n'+tady+'  minion_key update ok!')
    log.close()



